<?php

namespace app\controller;

use think\Request;
use app\service\AccountService;
use Exception;

class Account
{
    protected $accountService;

    public function __construct()
    {
        $this->accountService = new AccountService();
    }

    /**
     * 获取账号列表
     */
    public function index(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $filters = $request->only(['category_id', 'keyword', 'is_favorite']);

            $accounts = $this->accountService->getUserAccounts($userId, $filters);

            return success($accounts, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 获取账号详情
     */
    public function read(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $accountId = $request->param('id');

            if (empty($accountId)) {
                return error('账号ID不能为空');
            }

            $account = $this->accountService->getAccountDetail($userId, $accountId);

            return success($account, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 验证主密码并获取解密的账号详情
     */
    public function readDecrypted(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $accountId = $request->param('id');
            $masterPassword = $request->param('master_password');

            if (empty($accountId)) {
                return error('账号ID不能为空');
            }

            if (empty($masterPassword)) {
                return error('主密码不能为空');
            }

            $account = $this->accountService->getDecryptedAccountDetail($userId, $accountId, $masterPassword);

            return success($account, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 创建账号
     */
    public function save(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $data = $request->only([
                'category_id', 'title', 'username', 'password',
                'website', 'notes', 'icon', 'tags', 'is_favorite',
                'encrypt_method', 'encrypt_version', 'expires_at'
            ]);

            // 验证必填字段
            if (empty($data['title'])) {
                return error('账号标题不能为空');
            }

            // 处理加密字段
            if (!empty($data['username'])) {
                $data['username_encrypted'] = $data['username']; // 这里应该加密
                unset($data['username']);
            }

            if (!empty($data['password'])) {
                $data['password_encrypted'] = $data['password']; // 这里应该加密
                unset($data['password']);
            }

            if (!empty($data['notes'])) {
                $data['notes_encrypted'] = $data['notes']; // 这里应该加密
                unset($data['notes']);
            }

            $account = $this->accountService->createAccount($userId, $data);

            return success($account, '创建成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 更新账号
     */
    public function update(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $accountId = $request->param('id');
            $data = $request->only([
                'category_id', 'title', 'username', 'password',
                'website', 'notes', 'icon', 'tags', 'is_favorite',
                'encrypt_method', 'encrypt_version', 'expires_at'
            ]);

            if (empty($accountId)) {
                return error('账号ID不能为空');
            }

            if (empty($data['title'])) {
                return error('账号标题不能为空');
            }

            // 处理加密字段
            if (!empty($data['username'])) {
                $data['username_encrypted'] = $data['username']; // 这里应该加密
                unset($data['username']);
            }

            if (!empty($data['password'])) {
                $data['password_encrypted'] = $data['password']; // 这里应该加密
                unset($data['password']);
            }

            if (!empty($data['notes'])) {
                $data['notes_encrypted'] = $data['notes']; // 这里应该加密
                unset($data['notes']);
            }

            $account = $this->accountService->updateAccount($userId, $accountId, $data);

            return success($account, '更新成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 删除账号
     */
    public function delete(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $accountId = $request->param('id');

            if (empty($accountId)) {
                return error('账号ID不能为空');
            }

            $this->accountService->deleteAccount($userId, $accountId);

            return success(null, '删除成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 切换收藏状态
     */
    public function toggleFavorite(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $accountId = $request->param('id');

            if (empty($accountId)) {
                return error('账号ID不能为空');
            }

            $account = $this->accountService->toggleFavorite($userId, $accountId);

            return success($account, '操作成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 复制密码
     */
    public function copyPassword(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $accountId = $request->param('id');

            if (empty($accountId)) {
                return error('账号ID不能为空');
            }

            $this->accountService->copyPassword($userId, $accountId);

            return success(null, '操作成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 获取收藏账号
     */
    public function favorites(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件

            $accounts = $this->accountService->getFavoriteAccounts($userId);

            return success($accounts, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 搜索账号
     */
    public function search(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $keyword = $request->param('keyword');

            if (empty($keyword)) {
                return error('搜索关键词不能为空');
            }

            $accounts = $this->accountService->searchAccounts($userId, $keyword);

            return success($accounts, '搜索成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 获取即将过期的账号
     */
    public function expiring(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $days = $request->param('days', 7);

            $accounts = $this->accountService->getExpiringAccounts($userId, $days);

            return success($accounts, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 获取已过期的账号
     */
    public function expired(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件

            $accounts = $this->accountService->getExpiredAccounts($userId);

            return success($accounts, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 批量删除账号
     */
    public function batchDelete(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $accountIds = $request->param('account_ids');

            if (empty($accountIds) || !is_array($accountIds)) {
                return error('请选择要删除的账号');
            }

            $count = $this->accountService->batchDeleteAccounts($userId, $accountIds);

            return success(['count' => $count], "成功删除{$count}个账号");

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 批量更新分类
     */
    public function batchUpdateCategory(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $accountIds = $request->param('account_ids');
            $categoryId = $request->param('category_id');

            if (empty($accountIds) || !is_array($accountIds)) {
                return error('请选择要更新的账号');
            }

            $count = $this->accountService->batchUpdateCategory($userId, $accountIds, $categoryId);

            return success(['count' => $count], "成功更新{$count}个账号");

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 获取账号统计信息
     */
    public function stats(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件

            $stats = $this->accountService->getUserAccountStats($userId);

            return success($stats, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 导出账号数据
     */
    public function export(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $categoryId = $request->param('category_id');

            $accounts = $this->accountService->exportAccounts($userId, $categoryId);

            return success($accounts, '导出成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }
}